package com.xiaowenxiong.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.xiaowenxiong.entity.JsonObject;
import com.xiaowenxiong.entity.Student;
import com.xiaowenxiong.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * Created by 15c on 2017/6/11.
 */
@Controller
public class AjaxTestController {
    @Autowired
    StudentService studentService;

    @RequestMapping(value = "/getAjax", method = RequestMethod.GET)
    public String getJsp() throws IOException {
        return "ajaxTest/get";
    }


    @RequestMapping(value = "/getAjaxJsp", method = RequestMethod.GET)
    public String getAjaxJsp() throws IOException {
        return "ajaxTest/ajax";
    }

    @ResponseBody
    @RequestMapping(value = "/findStudent", method = RequestMethod.GET)
//    @GetMapping("/student")
    public String findOneStudent() {
        Student student = studentService.selectAstudentInfo("15001");
        JsonObject<Student> jsonObject = new JsonObject<Student>();
        jsonObject.setId(200);
        jsonObject.setMes("ok");
        jsonObject.setData(student);
        return JSON.toJSONString(jsonObject);
    }

    @RequestMapping(value = "/ajaxJsp", method = RequestMethod.GET)
    public String AjaxJsp() throws IOException {
        return "ajaxTest/getJSON";
    }

    @ResponseBody
    @RequestMapping(value = "/getStudent", method = RequestMethod.GET)
//    @GetMapping("/student")
    public String getOneStudent() {
        Student student = studentService.selectAstudentInfo("15001");
        JsonObject<Student> jsonObject = new JsonObject<Student>();
        jsonObject.setId(200);
        jsonObject.setMes("ok");
        jsonObject.setData(student);
        return JSON.toJSONString(jsonObject);
    }

    @RequestMapping(value = "/get_ajax_login", method = RequestMethod.GET)
    public String getAjaxLoginHtml() throws IOException {
        return "ajaxTest/ajax_login";
    }

    @ResponseBody
    @RequestMapping(value = "/ajax_login", method = RequestMethod.POST)
    public String login(@RequestParam(required = false) String account,
                        @RequestParam(required = false) String pass,
                        HttpServletRequest request) {
        System.out.print("account" + account + "<<<<<<<<<<<pass" + pass);
        JsonObject<String> jsonObject = new JsonObject<String>();
        if (account != null && pass != null && account.equals("wang") && pass.equals("wanggaowen")) {
            System.out.print("account" + account + "<<<<<<<<<<<pass" + pass);
            jsonObject.setData("yes");
            jsonObject.setId(200);
            jsonObject.setMes("ok");
            return JSON.toJSONString(jsonObject);
        } else {
            jsonObject.setData("no");
            jsonObject.setId(201);
            jsonObject.setMes("error");
            return JSON.toJSONString(jsonObject);
        }

    }

    @RequestMapping(value = "/fileUp", method = RequestMethod.GET)
    public String getFileUpJsp() throws IOException {
        return "ajaxTest/fileUp";
    }

    /**
     * 文件上传
     * @param request
     * @param base64
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/fileUp", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
    public String getFileUp(HttpServletRequest request, String base64) throws IOException {
            try {
                //去掉base64数据头部data:image/png;base64,和尾部的” " “
                String[] ww = base64.split(",");
                base64 = ww[1];
                String[] aa = base64.split("\"");
                base64 = aa[0];
                //获取扩展名
                String extensionName = ".png";
                // 图片保存到本地
                String path = request.getSession().getServletContext().getRealPath("/resource/img");
                //声明图片地址
                System.out.println("____________path"+path);
                String imgAddress = null;
                //以当前时间加随机数命名上传文件
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                String date = sdf.format(new java.util.Date());


                //设置图片名为当前时间加随机数
                imgAddress = date + new Random().nextInt() + extensionName;
                System.out.println("随机数" + new Random().nextInt());
                //解码
                decoderBase64File(base64, path, imgAddress);
                JsonObject<String> jsonObject = new JsonObject<String>();
                jsonObject.setId(200);
                jsonObject.setData(imgAddress);
                return JSON.toJSONString(jsonObject);
            } catch (Exception e) {
                e.getStackTrace();
                JsonObject<String> jsonObject = new JsonObject<String>();
                jsonObject.setId(202);
                jsonObject.setData("上传失败");
                return JSON.toJSONString(jsonObject);
            }

    }

    public static void decoderBase64File(String base64Code, String targetPath,String imgAddress) {
        byte[] buffer;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(targetPath + "/" + imgAddress);
            buffer = new BASE64Decoder().decodeBuffer(base64Code);
            out.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
